package com.uwaterloo.interviewme;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.uwaterloo.interviewme.am.ApplicationManager;
import com.uwaterloo.interviewme.exception.ServerException;

/**
 * The Class InterviewMeActivity is the entry point the this application.
 * 
 * It is a login view where users will input their credential.
 * 
 * On successful authentication, users will be bring to the {@link InterviewListRender}
 * 
 * On failed authentication, an error message will be prompted to the user and the user can re-login
 * as desired.
 */
public class InterviewMeActivity extends Activity {

	/** The Constant ERR_MSG. */
	private static final String ERR_MSG = "Authentication Fail. Please input the right username and password";

	/** The application manager. */
	private ApplicationManager am;

	/** The uw user id input box. */
	private EditText uwUserIdInputBox;

	/** The uw password input box. */
	private EditText uwPasswordInputBox;

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onCreate(android.os.Bundle)
	 */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		
		uwUserIdInputBox = (EditText) findViewById(R.id.uwUserIdEntry);
		uwPasswordInputBox = (EditText) findViewById(R.id.uwPasswordEntry);

		final Button loginButton = (Button) findViewById(R.id.loginLabel);
		loginButton.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				onLoginButtonClicked();
			}
		});
	}

	/**
	 * On login button clicked.
	 */
	private void onLoginButtonClicked() {
		String userName = uwUserIdInputBox.getText().toString();
		String pwd = uwPasswordInputBox.getText().toString();

		initAM(userName);
		try {
			if (am.login(pwd)) {
				renderInterviewList();
			} else {
				displayLoginErrorMsg();
			}
		} catch (ServerException e) {
			Toast.makeText(this, "Server unavailable. Try again later", Toast.LENGTH_LONG).show();
		}
	}

	/**
	 * Inits the am.
	 * 
	 * @param userName
	 */
	private void initAM(String userName) {
		am = ApplicationManager.createInstance(userName);
		am.setContext(this);
	}

	/**
	 * Render interview list.
	 */
	private void renderInterviewList() {
		Intent intent = new Intent(this, InterviewListRender.class);
		startActivity(intent);
	}

	/**
	 * Display login error msg.
	 */
	private void displayLoginErrorMsg() {
		final TextView textView = (TextView) findViewById(R.id.loginErrorMsg);
		textView.setText(ERR_MSG);
	}
}